<template>
  <div class="create-travel-note-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>编写游记</h1>
      <p class="subtitle">记录你的精彩旅程，分享美好回忆</p>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 表单区域 -->
      <el-card class="form-card" shadow="hover">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="travel-note-form"
        >
          <!-- 标题输入 -->
          <el-form-item label="游记标题" prop="title">
            <el-input
              v-model="form.title"
              placeholder="请输入游记标题"
              maxlength="100"
              show-word-limit
              clearable
              size="large"
            />
          </el-form-item>

          <!-- 封面图片上传 -->
          <el-form-item label="封面图片" prop="coverImage">
            <el-upload
              v-model:file-list="fileList"
              class="cover-uploader"
              :auto-upload="false"
              list-type="picture-card"
              :limit="1"
              :on-change="handleCoverChange"
              :on-exceed="handleExceed"
              :on-remove="handleCoverRemove"
              :on-preview="handlePictureCardPreview"
              accept="image/jpeg,image/png,image/webp"
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  请上传一张封面图片，大小不超过2MB
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <!-- 选择城市 -->
          <el-form-item label="旅行城市" prop="city">
            <el-select
              v-model="form.city"
              placeholder="选择旅行城市"
              filterable
              allow-create
              default-first-option
              clearable
              size="large"
            >
              <el-option
                v-for="city in popularCities"
                :key="city.value"
                :label="city.label"
                :value="city.value"
              />
            </el-select>
          </el-form-item>

          <!-- 旅行日期 -->
          <el-form-item label="旅行日期" prop="travelDate">
            <el-date-picker
              v-model="form.travelDate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              size="large"
              style="width: 100%"
            />
          </el-form-item>

          <!-- 游记内容 -->
          <el-form-item label="游记内容" prop="content">
            <div>
              <!-- 工具栏 -->
              <div id="toolbar-container" style="border: 1px solid #ccc; border-bottom: none; background-color: #fafafa; padding: 4px 0;"></div>
              <!-- 编辑器 -->
              <div id="editor-container" style="height: 400px; overflow-y: auto; border: 1px solid #ccc; border-top: none;"></div>
            </div>
            <div style="text-align: right; color: #909399; margin-top: 10px;">
              {{ form.content.length }}/10000
            </div>
          </el-form-item>

          <!-- 图片上传 -->
          <el-form-item label="旅行照片">
            <el-upload
              v-model:file-list="galleryFiles"
              class="gallery-uploader"
              :auto-upload="false"
              list-type="picture-card"
              :limit="9"
              :on-change="handleGalleryChange"
              :on-exceed="handleExceed"
              :on-remove="handleGalleryRemove"
              :on-preview="handlePictureCardPreview"
              accept="image/jpeg,image/png,image/webp"
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">最多上传9张图片，每张不超过2MB</div>
              </template>
            </el-upload>
          </el-form-item>

          <!-- 标签输入 -->
          <el-form-item label="添加标签">
            <div class="tags-container">
              <!-- 已添加的标签 -->
              <el-tag
                v-for="(tag, index) in form.tags"
                :key="tag"
                closable
                :disable-transitions="false"
                @close="form.tags.splice(index, 1)"
                class="tag-item"
              >
                {{ tag }}
              </el-tag>

              <!-- 标签输入框 -->
              <el-input
                v-if="form.tags.length < 6"
                v-model="inputTag"
                placeholder="输入标签后按回车确认"
                size="small"
                class="tag-input"
                @keyup.enter="handleTagInput"
                @keyup.space="handleTagInput"
                maxlength="10"
              />
            </div>

            <div class="tags-suggestions">
              <span class="suggestions-label">推荐标签：</span>
              <el-tag
                v-for="tag in suggestedTags"
                :key="tag"
                effect="plain"
                :closable="false"
                @click="addSuggestedTag(tag)"
                class="suggestion-tag"
              >
                {{ tag }}
              </el-tag>
            </div>
          </el-form-item>

          <!-- 公开设置 -->
          <el-form-item label="公开设置">
            <el-radio-group v-model="form.visibility" size="large">
              <el-radio-button label="public">公开</el-radio-button>
              <el-radio-button label="private">仅自己可见</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item class="form-actions">
            <el-button
              size="large"
              @click="handleCancel"
              :disabled="uploadingCover || uploadingGallery"
              >取消</el-button
            >
            <el-button
              type="primary"
              size="large"
              @click="handleSaveDraft"
              :loading="uploadingCover || uploadingGallery"
              :disabled="submitting"
              >{{
                uploadingCover || uploadingGallery ? '正在上传...' : '保存草稿'
              }}</el-button
            >
            <el-button
              type="success"
              size="large"
              @click="handleSubmit"
              :loading="submitting || uploadingCover || uploadingGallery"
              :disabled="uploadingCover || uploadingGallery"
              >{{
                uploadingCover || uploadingGallery ? '正在上传...' : '发布游记'
              }}</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { createTravelNote } from '../../api/travelNote'
import { uploadImage, uploadImages } from '../../api/upload'
import { authUtils } from '../../utils/auth'
// 导入 wangeditor
import '@wangeditor/editor/dist/css/style.css' // 引入样式
import { createEditor, createToolbar } from '@wangeditor/editor'

// 路由实例
const router = useRouter()

// 表单引用
const formRef = ref(null)

// 表单数据
const form = reactive({
  title: '',
  coverImage: '',
  city: '',
  travelDate: [],
  content: '',
  galleryImages: [],
  tags: [],
  visibility: 'public'
})

// 编辑器实例
let editor = null
let toolbar = null

// 编辑器配置
const editorConfig = {
  placeholder: '分享你的旅行故事...',
  onChange(editor) {
    // 监听内容变化，更新 form.content
    form.content = editor.getHtml()
  },
  MENU_CONF: {
    // 配置上传图片
    uploadImage: {
      // 自定义上传
      async customUpload(file, insertFn) {
        uploadingGallery.value = true
        try {
          const result = await uploadImage(file)
          if (result.success && result.data && result.data.url) {
            insertFn(result.data.url) // 插入图片到编辑器
            ElMessage.success('图片插入成功')
          } else {
            throw new Error(result.message || '上传失败')
          }
        } catch (error) {
          console.error('上传图片失败:', error)
          ElMessage.error('上传图片失败：' + (error.message || '请重试'))
        } finally {
          uploadingGallery.value = false
        }
      }
    }
  }
}

// 工具栏配置
const toolbarConfig = {
  excludeKeys: ['fullScreen'] // 排除不需要的功能
}

// 初始化编辑器
const initEditor = () => {
  // 创建编辑器实例
  editor = createEditor({
    selector: '#editor-container',
    config: editorConfig,
    mode: 'default'
  })
  
  // 创建工具栏实例
  toolbar = createToolbar({
    editor,
    selector: '#toolbar-container',
    config: toolbarConfig
  })
}

// 销毁编辑器
const destroyEditor = () => {
  if (editor) {
    editor.destroy()
    editor = null
  }
  if (toolbar) {
    toolbar.destroy()
    toolbar = null
  }
}

// 文件列表
const fileList = ref([])
const galleryFiles = ref([])
const inputTag = ref('')

// 上传相关状态
const submitting = ref(false)
const uploadingCover = ref(false)
const uploadingGallery = ref(false)

// 创建本地图片URL用于预览
const getImageUrl = (file) => {
  if (file.url) {
    return file.url
  } else if (file.raw) {
    return URL.createObjectURL(file.raw)
  }
  return ''
}

// 图片预览处理函数
const handlePreview = (uploadFile) => {
  // 在实际项目中可以打开大图预览
  console.log('预览图片:', uploadFile)
}

// 用于生成预览URL的处理函数
const handlePictureCardPreview = (file) => {
  // 确保文件对象有预览URL
  if (!file.url && file.raw) {
    file.url = URL.createObjectURL(file.raw)
  }
  // 在实际项目中可以打开大图预览
  console.log('预览图片:', file.url)
}

// 热门城市列表
const popularCities = ref([
  { label: '北京', value: '北京' },
  { label: '上海', value: '上海' },
  { label: '成都', value: '成都' },
  { label: '杭州', value: '杭州' },
  { label: '三亚', value: '三亚' },
  { label: '西安', value: '西安' },
  { label: '厦门', value: '厦门' },
  { label: '丽江', value: '丽江' },
  { label: '重庆', value: '重庆' },
  { label: '青岛', value: '青岛' }
])

// 推荐标签
const suggestedTags = [
  '美食',
  '风景',
  '文化',
  '历史',
  '购物',
  '休闲',
  '亲子',
  '情侣',
  '独自旅行',
  '自驾游',
  '背包客',
  '摄影',
  '打卡',
  '攻略',
  '小众景点'
]

// 处理标签输入
const handleTagInput = () => {
  if (
    inputTag.value &&
    inputTag.value.trim() &&
    !form.tags.includes(inputTag.value.trim()) &&
    form.tags.length < 6
  ) {
    form.tags.push(inputTag.value.trim())
    inputTag.value = ''
  }
}

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入游记标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  coverImage: [
    { required: true, message: '请上传封面图片', trigger: 'change' }
  ],
  city: [
    { required: true, message: '请选择或输入旅行城市', trigger: 'change' }
  ],
  travelDate: [
    { required: true, message: '请选择旅行日期', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入游记内容', trigger: 'blur' },
    { min: 50, message: '内容不能少于50个字符', trigger: 'blur' }
  ]
}

// 封面图片上传前验证
const beforeUploadCover = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片格式！')
    return false
  }

  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }

  return true
}

// 相册图片上传前验证
const beforeUploadGallery = (file) => {
  return beforeUploadCover(file)
}

// 处理封面文件变化（选择文件时）- 自动上传到七牛云
const handleCoverChange = async (uploadFile, uploadFiles) => {
  // 验证文件
  const valid = beforeUploadCover(uploadFile.raw)
  if (!valid) {
    // 如果验证失败，从文件列表中移除
    const index = uploadFiles.findIndex((file) => file.uid === uploadFile.uid)
    if (index > -1) {
      uploadFiles.splice(index, 1)
    }
    return
  }

  // 生成本地预览URL
  if (uploadFile.raw) {
    uploadFile.url = URL.createObjectURL(uploadFile.raw)
  }

  // 上传到七牛云
  uploadingCover.value = true
  try {
    const result = await uploadImage(uploadFile.raw)
    if (result.success && result.data && result.data.url) {
      form.coverImage = result.data.url // 提取 URL 字符串
      uploadFile.url = result.data.url // 更新为线上URL
      ElMessage.success('封面图片上传成功')
    } else {
      throw new Error(result.message || '上传失败')
    }
  } catch (error) {
    console.error('上传封面失败:', error)
    ElMessage.error('上传封面失败：' + (error.message || '请重试'))
    // 上传失败，移除文件
    const index = uploadFiles.findIndex((file) => file.uid === uploadFile.uid)
    if (index > -1) {
      uploadFiles.splice(index, 1)
    }
    form.coverImage = ''
  } finally {
    uploadingCover.value = false
  }
}

// 处理相册文件变化（选择文件时）- 自动上传到七牛云
const handleGalleryChange = async (uploadFile, uploadFiles) => {
  // 验证文件
  const valid = beforeUploadGallery(uploadFile.raw)
  if (!valid) {
    // 如果验证失败，从文件列表中移除
    const index = uploadFiles.findIndex((file) => file.uid === uploadFile.uid)
    if (index > -1) {
      uploadFiles.splice(index, 1)
    }
    return
  }

  // 生成本地预览URL
  if (uploadFile.raw) {
    uploadFile.url = URL.createObjectURL(uploadFile.raw)
  }

  // 上传到七牛云
  uploadingGallery.value = true
  try {
    const result = await uploadImage(uploadFile.raw)
    if (result.success && result.data && result.data.url) {
      const url = result.data.url
      uploadFile.url = url // 更新为线上URL
      // 确保不重复添加
      if (!form.galleryImages.includes(url)) {
        form.galleryImages.push(url)
      }
      ElMessage.success('图片上传成功')
    } else {
      throw new Error(result.message || '上传失败')
    }
  } catch (error) {
    console.error('上传图片失败:', error)
    ElMessage.error('上传图片失败：' + (error.message || '请重试'))
    // 上传失败，移除文件
    const index = uploadFiles.findIndex((file) => file.uid === uploadFile.uid)
    if (index > -1) {
      uploadFiles.splice(index, 1)
    }
  } finally {
    uploadingGallery.value = false
  }
}

// 上传失败处理（本地模式下可能不会调用，但保留以防万一）
const handleUploadError = () => {
  ElMessage.warning('本地模式下无需上传，图片仅用于预览')
}

// 文件超出限制处理
const handleExceed = (files, fileList) => {
  ElMessage.warning(`最多只能上传${fileList.length}个文件`)
}

// 移除封面图片
const handleCoverRemove = (file, fileList) => {
  form.coverImage = ''
  // 释放对象URL，避免内存泄漏
  if (file.url && file.url.startsWith('blob:')) {
    URL.revokeObjectURL(file.url)
  }
}

// 移除相册图片
const handleGalleryRemove = (file, fileList) => {
  // 使用文件的 URL 来匹配（可能是七牛云URL或本地blob URL）
  const imageUrl = file.url
  const index = form.galleryImages.indexOf(imageUrl)
  if (index > -1) {
    form.galleryImages.splice(index, 1)
  }
  // 释放对象URL，避免内存泄漏
  if (file.url && file.url.startsWith('blob:')) {
    URL.revokeObjectURL(file.url)
  }
}

// 添加推荐标签
const addSuggestedTag = (tag) => {
  if (!form.tags.includes(tag) && form.tags.length < 6) {
    form.tags.push(tag)
  }
}

// 取消操作
const handleCancel = () => {
  if (form.title || form.content || form.tags.length > 0 || form.coverImage) {
    ElMessageBox.confirm('是否放弃当前编辑内容？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        router.push('/travel-note')
      })
      .catch(() => {
        // 取消离开
      })
  } else {
    router.push('/travel-note')
  }
}

// 保存草稿
const handleSaveDraft = async () => {
  // 检查是否登录
  if (!authUtils.isLoggedIn()) {
    ElMessage.warning('请先登录')
    return
  }

  // 确保编辑器内容同步到表单
  if (editor) {
    form.content = editor.getHtml()
  }

  // 检查必填字段
  if (!form.title || !form.content) {
    ElMessage.warning('请至少填写标题和内容')
    return
  }

  submitting.value = true

  try {
    const submitData = {
      title: form.title,
      cover_image: form.coverImage || '',
      city: form.city || '',
      start_date: form.travelDate[0] || null,
      end_date: form.travelDate[1] || null,
      content: form.content,
      gallery_images: form.galleryImages,
      tags: form.tags,
      visibility: 'private', // 草稿设为私密
      status: 'draft'
    }

    const result = await createTravelNote(submitData)

    if (result.success) {
      ElMessage.success('草稿保存成功')
      // 可以选择留在当前页或跳转到游记列表
      setTimeout(() => {
        router.push('/travel-note')
      }, 1000)
    } else {
      ElMessage.error(result.message || '保存失败')
    }
  } catch (error) {
    console.error('保存草稿失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  // 检查是否登录
  if (!authUtils.isLoggedIn()) {
    ElMessage.warning('请先登录')
    return
  }

  // 确保编辑器内容同步到表单
  if (editor) {
    form.content = editor.getHtml()
  }

  try {
    await formRef.value.validate()
    submitting.value = true

    // 构建提交数据（符合后端 API 格式）
    const submitData = {
      title: form.title,
      cover_image: form.coverImage,
      city: form.city,
      start_date: form.travelDate[0] || null,
      end_date: form.travelDate[1] || null,
      content: form.content,
      gallery_images: form.galleryImages,
      tags: form.tags,
      visibility: form.visibility,
      status: form.visibility === 'public' ? 'pending' : 'draft'
    }

    console.log('提交的游记数据:', submitData)

    const result = await createTravelNote(submitData)

    if (result.success) {
      const msg =
        form.visibility === 'public'
          ? '游记已提交审核，审核通过后将在旅游圈展示'
          : '游记发布成功！'

      ElMessage.success(msg)

      // 跳转到游记列表
      setTimeout(() => {
        router.push('/travel-note')
      }, 1500)
    } else {
      ElMessage.error(result.message || '发布失败')
    }
  } catch (error) {
    if (error !== 'validation') {
      console.error('发布游记失败:', error)
      ElMessage.error('发布失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

// 生命周期钩子
onMounted(() => {
  // 延迟初始化，确保DOM已渲染
  setTimeout(() => {
    initEditor()
  }, 100)
})

onBeforeUnmount(() => {
  destroyEditor()
})
</script>

<style scoped>
.create-travel-note-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  color: #303133;
  margin-bottom: 10px;
  font-size: 28px;
}

.subtitle {
  color: #909399;
  font-size: 16px;
}

.main-content {
  margin-bottom: 40px;
}

.form-card {
  border-radius: 8px;
  overflow: hidden;
}

.travel-note-form {
  padding: 10px;
}

.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.cover-uploader .el-upload:hover {
  border-color: #409eff;
}

.gallery-uploader {
  margin-top: 10px;
}

.tags-suggestions {
  margin-top: 12px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.suggestions-label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.suggestion-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.suggestion-tag:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .create-travel-note-container {
    padding: 10px;
  }

  .form-actions {
    flex-direction: column;
  }

  .form-actions .el-button {
    width: 100%;
  }
}

.create-travel-note {
  padding: 20px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 32px;
}

.tag-item {
  height: 28px;
  line-height: 26px;
}

.tag-input {
  width: auto;
  flex: 1;
  min-width: 100px;
}

.tag-input .el-input__wrapper {
  box-shadow: none;
}

.tags-suggestions {
  margin-top: 12px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.suggestions-label {
  margin-right: 4px;
}
</style>
